package managers.messengerManager.services;

import java.util.ResourceBundle;

import managers.messengerManager.FeedbackManager;
import managers.messengerManager.MessengerManager;
import utils.ManagingMessage;
import utils.ManagingMessage.Type;
import utils.StackTracePrinter;
import utils.UserState;
public class ChangeStateService extends Service {


	private utils.UserState newState;

	private int baseWaitTime;


	public ChangeStateService (utils.UserState newState)  {
		this(newState, DEFAULT_BASE_WAIT_TIME);
	}

	public ChangeStateService (utils.UserState newState, int baseWaitTime)  {
		super("Change State");
		this.newState= newState;
		this.baseWaitTime = baseWaitTime;
	}


	public void undoChangeState() {
		manager.getFeedbackManager().updateStatus(ResourceBundle.getBundle("managers.messengerManager.services.messages").getString("m.4"), FeedbackManager.WARNING);
		manager.getFeedbackManager().changeState(MessengerManager.getSharedInstance().getState());
	}


	public void run() {

		try {
			manager.getFeedbackManager().changeState(newState);
			if (requestStateChange(newState)) {
				manager.getDataManager().getUser(manager.getUserId()).putProperty("state", newState);
				manager.setState(newState);
			} else {
				undoChangeState();
			}
		} catch (Exception e) {
			StackTracePrinter.print(e);
			undoChangeState();
		}
	}


	public synchronized boolean requestStateChange (UserState newState) throws Exception {
		ManagingMessage request = new ManagingMessage(Type.CHANGE_STATE_REQUEST);
		request.putProperty("userId", manager.getUserId());
		request.putProperty("state", newState);
		manager.getSingleProtocol().send(request, manager.getServerAddress(), manager.getServerPort());

		if (externalObject == null)
			Thread.currentThread().wait(baseWaitTime*2);
		if (externalObject != null && ((UserState)externalObject).equals(newState)) {
			externalObject = null;
			return true;
		} else {
			externalObject = null;
			return false;
		}
	}

}
